package pub.cleangao.mybatis.springboot;

import net.sf.jsqlparser.util.TablesNamesFinder;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;
import pub.cleangao.mybatis.runtime.Mode;
import java.util.Set;


/**
 * 分库、分表; 修改表名
 */
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class TableRenameInterceptor implements Interceptor {


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object paramObj = args[1];
        BoundSql boundSql = ms.getBoundSql(paramObj);
        String sql = boundSql.getSql();
        sql = prettySql(sql);
        Set<String> tables = TablesNamesFinder.findTables(sql);
        // 1. 原表查询
        if (!DataSourceContext.isTableNameChange()) {
            return invocation.proceed();
        }
        // 2. 分表(新表名)查询
        String newSql = sql;
        for (String tableName : tables) {
            String newTableName = DataSourceContext.getNewTableName(tableName);
            newSql = newSql.replace(tableName, newTableName);
        }
        newSql = prettySql(newSql);
        BoundSql bs = new BoundSql(ms.getConfiguration(), newSql, boundSql.getParameterMappings(), paramObj);
        for (ParameterMapping mapping : boundSql.getParameterMappings()) {
            String prop = mapping.getProperty();
            if (boundSql.hasAdditionalParameter(prop)) {
                Object parameter = boundSql.getAdditionalParameter(prop);
                bs.setAdditionalParameter(prop, parameter);
            }
        }
        MappedStatement newMs = copyFromMappedStatement(ms, new BoundSqlSqlSource(bs));
        args[0] = newMs;
        if (Mode.DEBUG) {
            sql = prettySql(sql);
            System.out.println("OldSQL:" + sql);
            System.out.println("NewSQL:" + newSql);
        }
        return invocation.proceed();
    }


    private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            builder.keyProperty(String.join(",", ms.getKeyProperties()));
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }

    private String prettySql(String sql) {
        sql = sql.replace("\r", " ");
        sql = sql.replace("\n", " ");
        sql = sql.replaceAll("\\s+", " ");
        return sql;
    }


    private record BoundSqlSqlSource(BoundSql boundSql) implements SqlSource {
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }


}
